package daos;

import java.util.ArrayList;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import entidades.Material;

public class MaterialDAO {
	private Session sesion;
	private Transaction tx;

	public Integer guardaMaterial(Material material) throws HibernateException {
		Integer id = 0;

		try {
			iniciaOperacion();
			id = (Integer) sesion.save(material);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}

		return id;
	}

	public void actualizaMaterial(Material material) throws HibernateException {
		try {
			iniciaOperacion();
			sesion.update(material);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}
	}

	public void eliminaMaterial(Material material) throws HibernateException {
		try {
			iniciaOperacion();
			sesion.delete(material);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}
	}

	public Material obtenMaterial(Integer idMaterialDeportivo)
			throws HibernateException {
		Material material = null;
		try {
			iniciaOperacion();
			material = (Material) sesion.get(Material.class,
					idMaterialDeportivo);
		} finally {
			sesion.close();
		}

		return material;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Material> obtenListaMaterial() throws HibernateException {
		ArrayList<Material> listaMaterial = new ArrayList<Material>();

		try {
			iniciaOperacion();
			listaMaterial = new ArrayList<Material>(sesion.createQuery("from Material").list());
		} finally {
			sesion.close();
		}

		return listaMaterial;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Material> consultarMaterial(String s) throws HibernateException {
		ArrayList<Material> listaMaterial = new ArrayList<Material>();

		try {
			iniciaOperacion();
			Query q = sesion.createSQLQuery("SELECT * FROM material WHERE tipo LIKE :string or descripcion LIKE :string").addEntity(Material.class);
//			Query q = sesion.createQuery("from Material as m where m.descripcion = :string");
			q.setParameter("string", "%"+ s+"%");
		
			listaMaterial = new ArrayList<Material>(q.list());
		} finally {
			sesion.close();
		}

		return listaMaterial;
	}
	
	private void iniciaOperacion() throws HibernateException {
		sesion = HibernateUtil.getSessionFactory().openSession();
		tx = sesion.beginTransaction();
	}

	private void manejaExcepcion(HibernateException he)
			throws HibernateException {
		tx.rollback();
		throw new HibernateException(
				"Ocurrió un error en la capa de acceso a datos", he);
	}

}
